import { ElMessage } from 'element-plus'
import { queryById } from '../api/user.js'
export default {
    state: {
        isOnline: false,
        userMessage: {},
    },
    mutations: {
        // 登录后改变状态
        changeOnline(state) {
            state.isOnline = !state.isOnline
        },
        //退出后改变状态，清空信息
        changeOffOnline(state) {
            state.isOnline = !state.isOnline
            state.userMessage = {}
        },
        //登录后，添加用户信息
        setUserMessage(state, value) {
            state.userMessage = value;
            state.isOnline=true;
        },
        //在修改用户信息后，后端通过后，可以直接在前端改变值
        changeUserMessage(state, value) {
            //考虑对象合并，并考虑不可回滚的错误
            try {
                Object.assign(state.userMessage, value)
            } catch (error) {
                console.log(error)
            }
        },
        getUserById(state) {
            if (state.isOnline) {
                queryById(state.userMessage.id).then((res) => {
                    if (res.code == '200') {
                        state.userMessage = res.data
                    } else {
                        ElMessage({
                            message: res.reason,
                            type: "error",
                        });
                    }
                })
            }else{
                ElMessage({
                    message:'请登录后再操作！',
                    type:"error"
                })
            }
        },
        //值修改人物头像
        changeHeader(state,url){
            state.userMessage.picture=url
        }

    },
    getters: {
        //过滤获取部分信息
        getShowDetail(state) {
           let  { tel, username, realName, gender, birth, picture, account, email, lastTime, school, academy } = state.userMessage
             return  { tel, username, realName, gender, birth, picture, account, email, lastTime, school, academy }
        },
        getNamePic(state){
           // let a={username,picture}=state.userMessage;
            return {username:state.userMessage.username,picture:state.userMessage.picture}
        },
        getId(state){
            return state.userMessage.id
        },
        getState(state){
            return state.isOnline
        },
        getUserName(state){
            return state.userMessage.username
        },
        getRole(state){
            return state.userMessage.role;
        },
        getSchool(state){
            return state.userMessage.school
        },
        getRealName(state){
            return state.userMessage.realName
        },
        getPic(state){
            return state.userMessage.picture
        },
        getAll(state){
            return state.userMessage
        }
    },
    actions: {
        // 异步向服务器获取当前用户信息
        refreshUserMessage(context) {
            setTimeout(() => {
                context.commit('getUserById')
            }, 0)
        }
    }
}